package com.sunxyz.cloudnote.web;

import com.sunxyz.cloudnote.dao.EntryDao;
import com.sunxyz.cloudnote.model.Entry;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author yangrd
 * @version 1.0.0
 * @date 2018/10/22
 **/
@RestController
@RequestMapping("/entry")
public class EntryController {

    private EntryDao entryDao;

    public EntryController(EntryDao entryDao) {
        this.entryDao = entryDao;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@RequestBody Entry entry){
        entryDao.save(entry);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("id") Entry entry){
        entryDao.delete(entry);
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void update(@PathVariable("id") Entry entry, @RequestBody Entry req){
        entry.setContent(req.getContent());
        entry.setTitle(req.getTitle());
    }

    @GetMapping("/{id}")
    public Entry get(@PathVariable("id") Entry entry){
        return entry;
    }

    @GetMapping
    public Page<Entry> getAll(Pageable pageable){
        return entryDao.findAll(pageable);
    }

}
